function md = madistd(data)
% madist  - Mahalanobis distance of single data argument 
%
% FORMAT:       md = madistd(data)
%
% Input fields:
%
%       data        RxC data
%
% Output fields:
%
%       md          Mahalonibis distance (of each row to sample mean/var)

% Version:  v0.8a
% Build:    9103020
% Date:     Otc-30 2009, 8:16 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin ~= 1 || ...
   ~isnumeric(data) || ...
    ndims(data) > 2 || ...
    size(data, 2) >= size(data, 1) || ...
    any(isinf(data(:)) | isnan(data(:))) || ...
   ~isreal(data)
    error( ...
        'BVQXtools:BadArgument', ...
        'Invalid argument supplied.' ...
    );
end

% make sure data is double
data = double(data);

% get number of rows
sd = size(data, 1);

% compute mean
m = (1 / sd) .* sum(data, 1);

% remove mean from data
data = data - m(ones(sd, 1), :);

% Q/R-de-compose data (matrix)
[Q,R] = qr(data,0);

% compute Mahalanobis distance
ri = R' \ data';
md = sum(ri .* ri, 1)' * (sd - 1);
